package ru.gerunn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DAO {
	
	public DAO() {
		
	}
	
	public Connection getConnection(String url, String username, String password) {
		Connection conn = null;
		try {
			Class.forName("com.ibm.db2.jcc.DB2Driver");
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
			while (e != null) {
				System.err.println("Error msg: " + e.getMessage());
				System.err.println("SQLSTATE: " + e.getSQLState());
				System.err.println("Error code: " + e.getErrorCode());
				e.printStackTrace();
				e = e.getNextException(); // For drivers that support chained exceptions
			}
		}

		return conn;
	}
	
	public static void main(String[] agrs) {
		try {
			Class.forName("com.ibm.db2.jcc.DB2Driver");
			System.out.println("**** Loaded the JDBC driver");
			
			Connection conn = DriverManager.getConnection("jdbc:db2://10.0.0.45:50000/LETDBACK", "db2inst1", "G]g.eJmd*59BP");
			System.out.println("**** Created a JDBC connection to the data source");
			
			Statement stmt = conn.createStatement();
			System.out.println("**** Created JDBC Statement object");
			
			ResultSet rs = stmt.executeQuery("select max(id) from logstest4.etdlog");
			System.out.println("**** Created JDBC ResultSet object");
			
			while (rs.next()) {
				System.out.println("max(id) = " + rs.getInt(1));
			}
			System.out.println("**** Fetched all rows from JDBC ResultSet");
			
			rs.close();
			System.out.println("**** Closed JDBC ResultSet");
			
			stmt.close();
			System.out.println("**** Closed JDBC Statement");
			
			conn.commit();
			System.out.println ( "**** Transaction committed" );
			
			conn.close();
			System.out.println("**** Disconnected from data source");
			
			System.out.println("**** JDBC Exit from class DAO - no errors");

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
			while (e != null) {
				System.err.println("Error msg: " + e.getMessage());
				System.err.println("SQLSTATE: " + e.getSQLState());
				System.err.println("Error code: " + e.getErrorCode());
				e.printStackTrace();
				e = e.getNextException(); // For drivers that support chained exceptions
			}
		}
	}

}
